# -*- coding: utf-8 -*-

"""
@project : TeleAI
@FileName: __init__.py
@Desc  :
"""

import logging as _logging
import os
import threading
import traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import WARN
#from ailog.mysql_log_handler import MysqlLogHandler

# Don't use this directly. Use _get_logger() instead.
_logger = None
_logger_lock = threading.Lock()

_level_names = {
    'FATAL': _logging.FATAL,
    'ERROR': _logging.ERROR,
    'WARN': _logging.WARN,
    'INFO': _logging.INFO,
    'DEBUG': _logging.DEBUG,
}

try:
    from Core import conf

    __name__ = conf.get(section='logging', option='name')
    log_file = conf.get(section='logging', option='file')
    log_level = conf.get(section='logging', option='level')
    mysql_log_level = conf.get(section='logging', option='mysql_level')
    log_level = _level_names[log_level]
    mysql_log_level = _level_names[mysql_log_level]
except:
    __name__ = 'AILOG'
    log_file = "ailog"
    log_level = _logging.INFO


def _get_logger():
    global _logger

    # Use double-checked locking to avoid taking lock unnecessarily.
    if _logger:
        return _logger

    _logger_lock.acquire()

    try:
        if _logger:
            return _logger

        logger = _logging.getLogger(__name__)
        logger.setLevel(level=log_level)
        handler = _logging.FileHandler(log_file, encoding='utf-8')
        formatter = _logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)

        ###
        console = _logging.StreamHandler()
        console.setLevel(_logging.INFO)
        logger.addHandler(console)
        

       
        # mysql_logger = MysqlLogHandler()
        # mysql_logger.setLevel(level=mysql_log_level)
        # logger.addHandler(mysql_logger)



        _logger = logger
        return _logger

    finally:
        _logger_lock.release()


_src_file = os.path.normcase(_get_logger.__code__.co_filename)
_logging._srcfile = _src_file



def log(level, msg, *args, **kwargs):
    _get_logger().log(level, msg, *args, **kwargs)


def debug(msg, *args, **kwargs):
    _get_logger().debug(msg, *args, **kwargs)


def error(msg, *args, **kwargs):
    try:
        # info(traceback.format_exc())
        _get_logger().error(msg,exc_info='{}'.format(traceback.format_exc()),*args, **kwargs)
    except:
        print(traceback.format_exc())

def fatal(msg, *args, **kwargs):
    _get_logger().fatal(msg, *args, **kwargs)


def info(msg, *args, **kwargs):
    _get_logger().info(msg, *args, **kwargs)


def warning(msg, *args, **kwargs):
    _get_logger().warning(msg, *args, **kwargs)


def set_verbosity(v):
    _get_logger().setLevel(v)


def set_log_file(path):
    global log_file
    log_file = path


_level_names = {
    FATAL: 'FATAL',
    ERROR: 'ERROR',
    WARN: 'WARN',
    INFO: 'INFO',
    DEBUG: 'DEBUG',
}
